<?php
/*
	 *   this controller is essentially the "Like Button" logic.
	 *   Its sole purpose for now is to work as a json_encode for
	 *   the AJAX calls for queries 
	 * 
*/
class LikesController extends AppController {
	var $name = 'Likes';

	function like($commentId = null) {
		/*  When a user clicks "like", this function is triggered
		 *  setting the like column to true and all other table fields
		 */
		$this->autoRender = false;
		
		$user = $this->Session->read('user');
		
		$this->Like->create();
		$this->Like->set('user_id', $user['User']['id']);
		$this->Like->set('comment_id', $commentId);
		$this->Like->set('like', 'true');
		$this->Like->save();
	}
	
	function unlike($commentId = null) {
		$this->autoRender = false;
		$user = $this->Session->read('user');
		
		$this->Like->query(
			"DELETE 
			 FROM likes
			 WHERE comment_id = " .$commentId. " && user_id = " .$user['User']['id']
		);
		
		//$this->Like->deleteByCommentId($commentId);
	}
	
	function getLikeUsers($commentId = null) {
		$this->autoRender = false;
		
		// get user_id, name, last name from a join (users and likes)
		$like_users = $this->Like->query(
			"SELECT l.user_id, u.first_name, u.last_name
			 FROM likes l, users u
			 WHERE l.comment_id = " .$commentId. " && l.user_id = u.id"
		);

		echo json_encode(array('forAjax' => $like_users));
	}
	
	/*
	 *  Code that was supposed to be used with displayComment.js for AJAX calls with facebook like button 
	 *  functionality, here just to show the logic with displayComments.js (which isn't being used either anymore)
	 *  
	 *  Instead I integrated the queries to be used with like button functionality / ajax calls into the blogs controller
	 * 
	 *
	
	function likesCount($commentId = null) {
		$this->autoRender = false;
		
		$likeCount = $this->Like->find('count', array(
			'conditions' => 
				array('Like.comment_id' => $commentId),
			'recursive' => -1)
		); 
		//end query
		
		echo json_encode(array('likeCount' => $likeCount));
	}
	
	function likesORnot($commentId = null) {
		$this->autoRender = false;
		
		$user = $this->Session->read('user');
		
		/*   Following query will return whether the current user "likes" ('like' field is a boolean)
		 *   the current comment or not.
		 * 
		 *   If yes, display option to unlike; if no, just display "like" => via JS
		 * /
		
		$likes = $this->Like->find('first', array(
			'conditions' => 
				array('Like.comment_id' => $commentId,
					'Like.user_id' => $user['User']['id']),
			'fields' => 'Like.like',
			'recursive' => -1)
		);  
		//end query
		
		echo json_encode(array('likes' => $likes));
	}
	
	*/
}
?>